package com.lanlian.cayman.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lanlian.cayman.LLApplication;
import com.lanlian.cayman.R;
import com.lanlian.cayman.utils.VolleyRequestUtils;
import com.lanlian.cayman.view.AccountTypeDialog;
import com.lanlian.cayman.view.ShowPictureDialog;
import com.lanlian.commonlib.base.BaseActivity;
import com.lanlian.commonlib.bean.BaseResponse;
import com.lanlian.commonlib.bean.PreRegisterInfo;
import com.lanlian.commonlib.bean.ReqGetPreRegister;
import com.lanlian.commonlib.bean.ReqVerifyInviteCode;
import com.lanlian.commonlib.bean.RespPreRegister;
import com.lanlian.commonlib.common.SystemConfig;
import com.lanlian.commonlib.event.EventCode;
import com.lanlian.commonlib.event.EventMessage;
import com.lanlian.commonlib.network.INetWorkCallback;
import com.lanlian.commonlib.upyun.IUploadFileCallback;
import com.lanlian.commonlib.upyun.MUploadFile;
import com.lanlian.commonlib.upyun.UploadPic;
import com.lanlian.commonlib.util.EventBusUtils;
import com.lanlian.imagelib.ShowImageUtils;
import com.lanlian.uikit.ActionItem;
import com.lanlian.uikit.CustomBottomSheetDialog;
import com.lanlian.uikit.CustomDialog;
import com.lanlian.utillib.CommonUtils;
import com.lanlian.utillib.DateUtils;
import com.lanlian.utillib.ImageUtils;
import com.lanlian.utillib.WorksSizeCheckUtil;

import java.io.File;
import java.io.InputStream;

import static com.lanlian.commonlib.common.SystemConfig.REQUEST_PERMISSIONS;

/**
 * <pre>
 *     author : huxiaobo
 *     e-mail : huxiaobo@xlanlian.com
 *     date   : 2018/11/6 10:00
 *     desc   : 开户第二步-开户须知
 *     version: 1.0
 * </pre>
 */
public class RegisterAgreementActivity extends BaseActivity implements View.OnClickListener {

    private ImageView mImgBack;
    private TextView mTvRisk2;
    private CheckBox mCbRisk2;
    private TextView mTvRisk3;
    private CheckBox mCbRisk3;
    private ImageView mImgAutograph;
    private ImageView mImgRiskDisclosure;
    private TextView mTvRiskTemplate;
    private CheckBox mCbRisk;
    private EditText mEtBino;
    private TextView mTvNext;
    private TextView mTvAccountType;
    private ImageView mImgTips;

    private String mAutographStr;
    private String mRiskDisclosureStr;
    private PreRegisterInfo mPreRegisterInfo;
    private RespPreRegister mRespPreRegister;

    private CustomBottomSheetDialog mBottomSheetDialog;
    private boolean mIsEditHasContent;
    private int mAccountType;
    private AccountTypeDialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_agreement);
        initPermission();
        initView();
        setListeners();
        getPreRegisterInfo();
        mBottomSheetDialog = new CustomBottomSheetDialog(this, "请选择");
        mBottomSheetDialog.addAction(new ActionItem("拍照"));
        mBottomSheetDialog.addAction(new ActionItem("从相册中选取"));
        mBottomSheetDialog.setOnItemClickListener(new CustomBottomSheetDialog.OnItemOnClickListener() {
            @Override
            public void onItemClick(ActionItem item, int position) {
                switch (item.mTitle) {
                    case "拍照":
                        openSysCamera();
                        break;
                    case "从相册中选取":
                        openSysAlbum();
                        break;
                    default:
                        break;
                }
            }
        });
    }

    @Override
    protected void initView() {
        super.initView();
        mImgBack = findViewById(R.id.img_back);
        mTvRisk2 = findViewById(R.id.tv_risk2);
        mCbRisk2 = findViewById(R.id.cb_risk2);
        mTvRisk3 = findViewById(R.id.tv_risk3);
        mCbRisk3 = findViewById(R.id.cb_risk3);
        mImgAutograph = findViewById(R.id.img_autograph);
        mImgRiskDisclosure = findViewById(R.id.img_risk_disclosure);
        mTvRiskTemplate = findViewById(R.id.tv_risk_template);
        mCbRisk = findViewById(R.id.cb_risk);
        mEtBino = findViewById(R.id.et_bino);
        mTvNext = findViewById(R.id.tv_next);
        mTvAccountType = findViewById(R.id.tv_account_type);
        mImgTips = findViewById(R.id.img_tips);
    }

    @Override
    protected void setListeners() {
        super.setListeners();
        mImgBack.setOnClickListener(this);
        mTvRisk2.setOnClickListener(this);
        mTvRisk3.setOnClickListener(this);
        mTvRiskTemplate.setOnClickListener(this);
        mImgAutograph.setOnClickListener(this);
        mImgRiskDisclosure.setOnClickListener(this);
        mTvNext.setOnClickListener(this);
        mImgTips.setOnClickListener(this);
        mCbRisk2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                checkData();
                if (isChecked) {
                    startActivity(new Intent(RegisterAgreementActivity.this, AgreementActivity.class)
                            .putExtra("type", 1));
                }
            }
        });
        mCbRisk3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                checkData();
                if (isChecked) {
                    startActivity(new Intent(RegisterAgreementActivity.this, AgreementActivity.class)
                            .putExtra("type", 3));
                }
            }
        });
        mCbRisk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                checkData();
            }
        });
        WorksSizeCheckUtil worksSizeCheckUtil = new WorksSizeCheckUtil(mTvNext);
        worksSizeCheckUtil.addAllEditText(mEtBino);
        worksSizeCheckUtil.setChangeListener(new WorksSizeCheckUtil.IEditTextChangeListener() {
            @Override
            public void textChange(boolean isHasContent) {
                mIsEditHasContent = isHasContent;
                LLApplication.reqUserRegister.setBiNo(mEtBino.getText().toString());
                checkData();
            }
        });
    }

    private void setAccountType() {
        //"为方便您以后在Lion Brokers 交易，拟为您开设全球通账户，请仔细阅读以下开户文件："
        mTvAccountType.setText("");
        String str1 = mAccountType == 0 ? "全球通账户" : "标准账户";
        SpannableString spString1 = new SpannableString(str1);
        spString1.setSpan(new ClickableSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(getResources().getColor(R.color.color_4385F3));
                ds.setFlags(Paint.UNDERLINE_TEXT_FLAG);
            }

            @Override
            public void onClick(View view) {
                if (dialog == null) {
                    dialog = new AccountTypeDialog(RegisterAgreementActivity.this, new AccountTypeDialog.OnChooseListener() {
                        @Override
                        public void onChoose(int accountType) {
                            mAccountType = accountType;
                            LLApplication.reqUserRegister.setAccountType(mAccountType);
                            setAccountType();
                        }
                    }, mAccountType);
                }
                dialog.show();
            }
        }, 0, str1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTvAccountType.append("为方便您以后在Lion Brokers 交易，拟为您开设");
        mTvAccountType.append(spString1);
        mTvAccountType.append("，请仔细阅读以下开户文件：");
        mTvAccountType.setMovementMethod(LinkMovementMethod.getInstance());
    }

    /**
     * 获取预开户信息
     */
    public void getPreRegisterInfo() {
        ReqGetPreRegister reqGetPreRegister = new ReqGetPreRegister();
        reqGetPreRegister.setMobile(LLApplication.reqUserRegister.getMobile());
        VolleyRequestUtils.getInstance().getPreRegister(this.toString(), reqGetPreRegister, new INetWorkCallback() {
            @Override
            public void onSuccess(Object response) {
                mRespPreRegister = (RespPreRegister) response;
                mPreRegisterInfo = mRespPreRegister.getData();
                if (mPreRegisterInfo != null) {
                    setPreRegisterInfo();
                } else {
                    setAccountType();
                }
            }

            @Override
            public void onFail(BaseResponse baseResponse) {
            }
        });
    }

    private void setPreRegisterInfo() {
        mRiskDisclosureStr = mPreRegisterInfo.getRiskDisclosure();
        mAutographStr = mPreRegisterInfo.getAutograph();
        if (!TextUtils.isEmpty(mPreRegisterInfo.getInviteCode())) {
            mEtBino.setText(mPreRegisterInfo.getInviteCode());
            mEtBino.setSelection(mPreRegisterInfo.getInviteCode().length());
        }
        LLApplication.reqUserRegister.setBiNo(mPreRegisterInfo.getInviteCode());
        LLApplication.reqUserRegister.setRiskDisclosure(mRiskDisclosureStr);
        LLApplication.reqUserRegister.setAutograph(mAutographStr);
        LLApplication.reqUserRegister.setMale(mPreRegisterInfo.getMale());
        LLApplication.reqUserRegister.setAccountType(mPreRegisterInfo.getAccountType());
        if (!TextUtils.isEmpty(mRiskDisclosureStr)) {
            ShowImageUtils.showImageView(this, SystemConfig.IMAGE_BASE_URL + mRiskDisclosureStr,
                    SystemConfig.IMG_DEFAULT_BACKGROUND, mImgRiskDisclosure);
        }
        if (!TextUtils.isEmpty(mAutographStr)) {
            ShowImageUtils.showImageView(this, SystemConfig.IMAGE_BASE_URL + mAutographStr,
                    SystemConfig.IMG_DEFAULT_BACKGROUND, mImgAutograph);
        }
        mAccountType = mPreRegisterInfo.getAccountType();
        setAccountType();
    }

    private void checkData() {
        if (!TextUtils.isEmpty(mAutographStr) && !TextUtils.isEmpty(mRiskDisclosureStr) && mIsEditHasContent
                && mCbRisk.isChecked() && mCbRisk2.isChecked() && mCbRisk3.isChecked()) {
            mTvNext.setEnabled(true);
            mTvNext.setClickable(true);
            mTvNext.setBackgroundResource(R.mipmap.login_btn);
        } else {
            mTvNext.setEnabled(false);
            mTvNext.setClickable(false);
            mTvNext.setBackgroundResource(R.drawable.bg_click_false);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.tv_next:
                ReqVerifyInviteCode reqVerifyInviteCode = new ReqVerifyInviteCode();
                reqVerifyInviteCode.setInviteCode(mEtBino.getText().toString());
                VolleyRequestUtils.getInstance().verifyInviteCode(this.toString(), reqVerifyInviteCode, new INetWorkCallback() {
                    @Override
                    public void onSuccess(Object response) {
                        startActivity(new Intent(RegisterAgreementActivity.this, OpenAccentActivity.class));
                    }

                    @Override
                    public void onFail(BaseResponse baseResponse) {
                        showToast(baseResponse.getMsg());
                    }
                });
                break;
            case R.id.tv_risk2:
                if (mCbRisk2.isChecked()) {
                    startActivity(new Intent(this, AgreementActivity.class)
                            .putExtra("type", 1));
                } else {
                    mCbRisk2.setChecked(true);
                }
                break;
            case R.id.tv_risk3:
                if (mCbRisk3.isChecked()) {
                    startActivity(new Intent(this, AgreementActivity.class)
                            .putExtra("type", 3));
                } else {
                    mCbRisk3.setChecked(true);
                }
                break;
            case R.id.img_back:
                postMessage();
                finish();
                break;
            case R.id.img_risk_disclosure:
                mImgRiskDisclosure.setTag(true);
                mBottomSheetDialog.showDialog();
                break;
            case R.id.img_autograph:
                startActivityForResult(new Intent(this, SignatureActivity.class), 1234);
                break;
            case R.id.tv_risk_template:
                new ShowPictureDialog(this, R.mipmap.risk).show();
                break;
            case R.id.img_tips:
                new CustomDialog(this, new CustomDialog.OnClickListener() {
                    @Override
                    public void onLeftClick() {
                    }

                    @Override
                    public void onRightClick() {
                    }
                }).setOneBtn(true).setRight("关闭").setTitle("若无邀请码，请填写<font color='#FF3347'>1000182</font>").show();
                break;
            default:
                break;
        }
    }

    /**
     * 打开系统相机
     */
    private void openSysCamera() {
        File outPutFile = new File(ImageUtils.IMAGE_SAVE_PATH, "output.png");
        Uri imageUri;
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(this, getPackageName()
                    + ".provider", outPutFile);
        } else {
            imageUri = Uri.fromFile(outPutFile);
        }
        //启动相机程序
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, SystemConfig.REQUEST_TAKE_PHOTO);
    }

    /**
     * 打开系统相册
     */
    private void openSysAlbum() {
        Intent albumIntent = new Intent(Intent.ACTION_PICK);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(albumIntent, SystemConfig.REQUEST_GALLERY);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case SystemConfig.REQUEST_TAKE_PHOTO:
                    savePic(getImageUri());
                    break;
                case SystemConfig.REQUEST_GALLERY:
                    savePic(data.getData());
                    break;
                case 1234:
                    String urlPath = data.getStringExtra("urlPath");
                    showLoadingDialog("上传中");
                    UploadPic.uploadFileWithCompress(this, urlPath, new IUploadFileCallback() {
                        @Override
                        public void onProgress(int percent) {
                            Log.e("upload", percent + "");
                        }

                        @Override
                        public void onData(Object output) {
                            dismissLoadingDialog();
                            MUploadFile mUploadFile = (MUploadFile) output;
                            if (mUploadFile.isResult()) {
                                showToast("上传成功");
                                mImgAutograph.setImageBitmap(BitmapFactory.decodeFile(urlPath));
                                mAutographStr = mUploadFile.getUrl();
                                LLApplication.reqUserRegister.setAutograph(mAutographStr);
                                checkData();
                            } else {
                                showToast("上传失败，请重试");
                            }
                        }
                    });
                    break;
                default:
                    break;
            }
        }
    }

    private void savePic(Uri imageUri) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = false;
            InputStream inputStream = getContentResolver().openInputStream(imageUri);
            BitmapFactory.decodeStream(inputStream, null, options);
            inputStream.close();
            int height = options.outHeight;
            int width = options.outWidth;
            int sampleSize = 1;
            int max = Math.max(height, width);
            if (max > 769) {
                int nw = width / 2;
                int nh = height / 2;
                while ((nw / sampleSize) > 769 || (nh / sampleSize) > 769) {
                    sampleSize *= 2;
                }
            }
            options.inSampleSize = sampleSize;
            options.inJustDecodeBounds = false;
            Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri), null, options);
            String fileName = DateUtils.longToString(System.currentTimeMillis(), "yyyyMMddHHmmssSSS") +
                    (int) ((Math.random() * 9 + 1) * 100);
            String urlPath = ImageUtils.saveBitmap(this, bitmap, fileName + ".jpg");
            showLoadingDialog("上传中");
            UploadPic.uploadFileWithCompress(this, urlPath, new IUploadFileCallback() {
                @Override
                public void onProgress(int percent) {
                    Log.e("upload", percent + "");
                }

                @Override
                public void onData(Object output) {
                    dismissLoadingDialog();
                    MUploadFile mUploadFile = (MUploadFile) output;
                    if (mUploadFile.isResult()) {
                        showToast("上传成功");
                        setImageView(bitmap);
                        saveImagePath(mUploadFile);
                        checkData();
                    } else {
                        showToast("上传失败，请重试");
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取图片裁剪Uri
     */
    private Uri getImageUri() {
        File outPutFile = new File(ImageUtils.IMAGE_SAVE_PATH, "output.png");
        Uri imageUri;
        int degree = ImageUtils.readPictureDegree(outPutFile.getPath());
        File file;
        if (degree != 0) {
            String path = ImageUtils.amendRotatePhoto(outPutFile.getPath(), degree, "output.png");
            file = new File(path);
        } else {
            file = outPutFile;
        }
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(this, getPackageName()
                    + ".provider", file);
        } else {
            imageUri = Uri.fromFile(file);
        }
        return imageUri;
    }

    private void setImageView(Bitmap bitmap) {
        mImgRiskDisclosure.setImageBitmap(bitmap);
    }

    private void saveImagePath(MUploadFile mUploadFile) {
        mRiskDisclosureStr = mUploadFile.getUrl();
        LLApplication.reqUserRegister.setRiskDisclosure(mRiskDisclosureStr);
    }

    @Override
    public void onBackPressed() {
        postMessage();
        super.onBackPressed();
    }

    private void postMessage() {
        EventBusUtils.post(new EventMessage(EventCode.EVENT_PRE_REGISTER));
    }

    /**
     * 初始化相机相关权限
     * 适配6.0+手机的运行时权限
     */
    private void initPermission() {
        String[] permissions = new String[]{Manifest.permission.CAMERA};
        //检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            // 之前拒绝了权限，但没有点击 不再询问 这个时候让它继续请求权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.CAMERA)) {
                ActivityCompat.requestPermissions(this, permissions, REQUEST_PERMISSIONS);
            } else {
                //注册相机权限
                ActivityCompat.requestPermissions(this, permissions, REQUEST_PERMISSIONS);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSIONS:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //成功
                    Toast.makeText(this, "用户授权相机权限", Toast.LENGTH_SHORT).show();
                } else {
                    // 勾选了不再询问
                    Toast.makeText(this, "用户拒绝相机权限", Toast.LENGTH_SHORT).show();
                    Intent intent = CommonUtils.getAppDetailSettingIntent(this);
                    startActivity(intent);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }

    @Override
    public void onReceiveEvent(EventMessage event) {
        super.onReceiveEvent(event);
        switch (event.getCode()) {
            case EventCode.EVENT_OPEN_ACCOUNT:
                finish();
                break;
            default:
                break;
        }
    }

}
